package com.qiaoyanqing.textdemoqyq7.AsyncTasks;

import android.os.AsyncTask;
import android.util.Log;

import com.qiaoyanqing.textdemoqyq7.Beans.Baike;
import com.qiaoyanqing.textdemoqyq7.CallBacks.BaikeCB;
import com.qiaoyanqing.textdemoqyq7.Utils.MyHttpUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/11/14.
 */

public class BaikeAsyncTask extends AsyncTask<String,Void,List<Baike>> {
    private List<Baike>mData=new ArrayList<>();
    private BaikeCB mBaikeCB;

    public BaikeAsyncTask(BaikeCB baikeCB) {
        mBaikeCB = baikeCB;
    }

    @Override
    protected List<Baike> doInBackground(String... strings) {
       String result= MyHttpUtils.getStringFromUrl(strings[0]);
        List<Baike>list=parseJson(result);

        return list;
    }

    private List<Baike> parseJson(String result) {
        try {
            JSONObject jsonObject=new JSONObject(result);
            JSONArray jsonArray=jsonObject.optJSONArray("data");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject1=jsonArray.optJSONObject(i);
                Baike baike=new Baike();
                baike.setId(jsonObject1.optString("id"));
                baike.setTitle(jsonObject1.optString("title"));
                baike.setCreate_time(jsonObject1.optString("create_time"));
                baike.setDescription(jsonObject1.optString("description"));
                baike.setNickname(jsonObject1.optString("nickname"));
                baike.setSource(jsonObject1.optString("source"));
                baike.setWap_thumb(jsonObject1.optString("wap_thumb"));
                mData.add(baike);
            }
            Log.d("flag", "------baikeparseJson: "+mData.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return mData;
    }

    @Override
    protected void onPostExecute(List<Baike> baikes) {
        super.onPostExecute(baikes);
        if (baikes != null) {
            mBaikeCB.senddata(baikes);
        }
    }
}
